using Beauty.Net.Cache;
using Beauty.Net.Integration;
using Beauty.Net.Kafka;
using Beauty.Net.Middleware;
using Beauty.Net.Middleware.Core;
using Beauty.Net.Ocelot.Core;
using Beauty.Net.RabbitMQ;
using Ocelot.Middleware;
using Beauty.Net.MongoDB;
using Beauty.Net.Elasticsearch;
using Beauty.Net.JsonWebToken;
using Beauty.Net.MiniExcel;

namespace Beauty.NetWebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // 配置JWT服务
            builder.Services.AddJwtService(options =>
            {
                options.SecretKey = "YourStrongSecretKeyHere";
                options.Issuer = "YourApplication";
                options.Audience = "YourApplication";
                options.AccessTokenExpirationMinutes = 30;
                options.RefreshTokenExpirationHours = 24;
                options.ValidateToken = true;
            });

            // 使用Action配置委托方式注册RabbitMQ服务
            builder.Services.AddRabbitMQ(options =>
            {
                // 直接在代码中配置RabbitMQ连接参数
                options.HostName = "localhost";
                options.Port = 5672;
                options.UserName = "guest";
                options.Password = "guest";
                options.VirtualHost = "/";
                options.Heartbeat = 60;
                options.ConnectionTimeout = 30000;
            });

            // 使用Action配置委托方式注册Kafka服务
            builder.Services.AddKafka(options =>
            {
                // 直接在代码中配置Kafka连接参数
                options.BootstrapServers = "localhost:9092";
                options.GroupId = "test-group";
                options.EnableAutoCommit = true;
                options.AutoCommitIntervalMs = 5000;
                options.SessionTimeoutMs = 30000;
                options.AutoOffsetReset = "earliest";
                options.SecurityProtocol = "Plaintext";
                options.SaslMechanism = "Plain";
                options.SaslUsername = "guest";
                options.SaslPassword = "guest";
            });

            // 注册MongoDB服务
            builder.Services.AddMongoDBService(options =>
            {
                options.ConnectionString = "mongodb://localhost:27017";
                options.DatabaseName = "MyDatabase";
                options.ConnectTimeoutSeconds = 30;
                options.UseSsl = false;
            });

            // 注册Elasticsearch服务
            builder.Services.AddElasticsearch(options =>
            {
                options.Nodes = new List<string> { "http://localhost:9200" };
                options.ConnectionTimeout = 5000;
                options.SocketTimeout = 30000;
                options.EnableSsl = false;
            });

            // 注册内存缓存服务
            builder.Services.AddMemoryCacheService();

            // 如需使用Redis缓存，可以取消下面的注释并配置连接字符串
            // builder.Services.AddRedisCacheService("127.0.0.1:6379");

            // 添加全局日志中间件服务，使用控制台存储（默认）
            builder.Services.AddGlobalLoggingMiddleware(options =>
            {
                // 可以根据需要配置日志存储类型和选项
                // 默认为控制台，可以改为 MySql、Elasticsearch 或 MongoDB
                options.StorageType = LogStorageType.Console;
                // 如果选择使用MySQL，可以取消下面的注释并配置连接字符串
                // options.MySqlConnectionString = "server=localhost;database=ApiLogs;user=root;password=password;";
                // options.MySqlTableName = "ApiLogs";
                // 是否记录请求体
                options.LogRequestContent = true;
                // 是否记录响应体
                options.LogResponseContent = true;
                // 排除的路径
                options.ExcludePaths = new[] { "/swagger", "/health" };
                // 最大日志大小
                options.MaxLogSize = 1024 * 512; // 512KB
            });

            // 配置微服务架构（包括服务发现和网关）
            builder.ConfigureMicroservices();

            // 配置网关路由
            builder.Services.ConfigureGatewayRoutes(routes =>
            {
                routes.Add(new ApiRouteOptions
                {
                    RouteKey = "api_route",
                    UpstreamPathTemplate = "/api/{everything}",
                    UpstreamHttpMethod = new List<string> { "GET", "POST", "PUT", "DELETE" },
                    ServiceName = "Beauty.NetWebApi", // 服务名称，将在Consul中注册
                    DownstreamPathTemplate = "/api/{everything}",
                    DownstreamScheme = "http",
                    LoadBalancerOptions = "RoundRobin"
                });

                routes.Add(new ApiRouteOptions
                {
                    RouteKey = "health_route",
                    UpstreamPathTemplate = "/health",
                    UpstreamHttpMethod = new List<string> { "GET" },
                    DownstreamPathTemplate = "/health",
                    DownstreamScheme = "http",
                    ServiceName = "Beauty.NetWebApi"
                });

                routes.Add(new ApiRouteOptions
                {
                    RouteKey = "swagger_route",
                    UpstreamPathTemplate = "/swagger/{everything}",
                    UpstreamHttpMethod = new List<string> { "GET" },
                    DownstreamPathTemplate = "/swagger/{everything}",
                    DownstreamScheme = "http",
                    ServiceName = "Beauty.NetWebApi"
                });
            });

            // 在Program.cs中注册服务
            builder.Services.AddMiniExcel();


            // 添加健康检查
            builder.Services.AddHealthChecks();

            // 添加控制器服务
            builder.Services.AddControllers();

            // 添加API文档服务
            builder.Services.AddEndpointsApiExplorer();

            // 配置Swagger生成器
            builder.Services.AddSwaggerGen(options =>
            {
                // 获取XML文档文件路径
                var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                // 配置Swagger读取XML注释，并包含继承的XML注释
                options.IncludeXmlComments(xmlPath, true);
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            // 在开发环境启用Swagger
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            // 启用路由中间件
            app.UseRouting();
            // 启用授权中间件
            app.UseAuthorization();

            // 使用全局日志中间件
            app.UseMiddleware<GlobalLoggingMiddleware>();

            // 使用响应包装中间件
            app.UseMiddleware<ResponseWrapperMiddleware>();

            // 使用健康检查端点
            app.UseDefaultHealthChecks();

            // 启动所有已注册的RabbitMQ消费者
            app.UseRabbitMQConsumers();

            // 使用微服务中间件（服务发现和网关）
            // 注意：如果此服务是网关服务，则设置useGateway=true；如果是普通微服务，则设置useGateway=false
            app.UseMicroservices(useGateway: true);

            // 确保使用Ocelot中间件
            app.UseOcelot().Wait();

            // 映射控制器路由
            app.MapControllers();

            // 使用不同的端口避免冲突
            app.Run();
        }
    }
}

